﻿@using SmartStore.Core.Domain.Forums;
@using SmartStore.Web.Models.Boards;
@using SmartStore.Web.Framework.UI;
@model ForumSearchResultModel
@{   
    var suggestions = new string[0];
    var encodedTerm = Model.Term.EmptyNull().HtmlEncode();
    var encodedAttemptedTerm = Model.AttemptedTerm.EmptyNull().HtmlEncode();

    if (encodedTerm.HasValue())
    {
        Html.AddTitleParts(T("Search.PageTitle", "\"" + encodedTerm + "\""));
    }
    else
    {
        Html.AddTitleParts(T("Forum.Search"));
    }

    if (Model.TotalCount > 0)
    {
        suggestions = Model.SearchResult.SpellCheckerSuggestions;
    }

    Layout = "_Layout";
}

<div class="page forum-search">
    <div class="page-title">
        <h1 class="h3">
			@if (encodedTerm.HasValue())
			{
				@T("Search.PageTitle", "<small class='search-term'>" + encodedTerm + "</small>")
			}
			else
			{
                @T("Forum.Search")
			}
        </h1>
    </div>

    <div class="page-body">
        <div class="search-input mt-4">
            @if (Model.AllowFiltering && Model.SearchResult.Facets.Any())
            {
                <div class="mb-4">
                    @{ Html.RenderAction("Filters", new { model = Model }); }
                </div>
            }

            <div class="w-75 mb-4">
                @{ Html.RenderAction("SearchBox", "Boards"); }
            </div>

		    @if (encodedAttemptedTerm.HasValue())
		    {
			    <div class="alert alert-warning">
				    @T("Search.TermCorrectedHint", "<strong>\"" + encodedTerm + "\"</strong>", "<strong>\"" + encodedAttemptedTerm + "\"</strong>")
			    </div>
		    }

		    @if (Model.Error.HasValue())
		    {
			    <div class="alert alert-danger">
				    @Model.Error
			    </div>
		    }
		    else if (Model.TotalCount == 0 && encodedTerm.HasValue())
		    {
			    <div class="alert alert-info">
				    @T("Forum.SearchNoResultsText")
			    </div>
		    }

		    @if (suggestions.Any())
		    {
			    <p class="search-suggestions">
				    <strong>@(T(encodedAttemptedTerm.HasValue() || Model.TotalCount == 0 ? "Search.DidYouMean" : "Search.RelatedSearchTerms")):</strong>
				    @{ 
					    var links = string.Join(", ", suggestions.Select(x => "<a href='" + Url.RouteUrl("BoardSearch", new { q = x }) + "'>{0}</a>".FormatCurrentUI(x)));
				    }
				    @Html.Raw(links)
			    </p>
		    }
        </div>

        @if (Model.TotalCount > 0)
        {
            <div class="fsearch-actions fsearch-actions--top d-flex flex-wrap">
                @if (Model.AllowSorting)
                {
                    <div class="fsearch-actions--sort">
                        @{ Html.RenderPartial("Product.List.FilterSort", Model); }
                    </div>
                }

                <div id="SearchHitsCount" class="fsearch-actions--page ml-auto pt-3">
                    @SearchHitCount()
                </div>
            </div>
        }

        <div class="search-results mt-3">
            <div class="topics-group table-responsive">
                @if (Model.TotalCount > 0)
                {
                    <table id="ForumSearchResult" class="table">
                        <thead>
                            <tr>
                                <th></th>
                                <th class="topic-name">
                                    @T("Forum.TopicTitle")
                                </th>
                                <th class="replies">
                                    @T("Forum.Replies")
                                </th>
                                <th class="views">
                                    @T("Forum.Views")
                                </th>
                                <th class="last-post">
                                    @T("Forum.LatestPost")
                                </th>
                            </tr>
                        </thead>
                        @{ Html.RenderPartial("SearchHits"); }
                    </table>
                }
            </div>
        </div>
    </div>
</div>

@helper SearchHitCount()
{
    var countHtml = "<span class='cumulative-count'>{0}</span>".FormatInvariant(Model.CumulativeHitCount.ToString("N0"));
    if (Model.SearchResult.Hits.HasNextPage)
    {
        countHtml += "<span class='more-hits-sign'>+</span>";
    }

    @T("Search.HitsFor", countHtml, "<b class='font-weight-medium'>{0}</b>".FormatInvariant(Model.Term.NaIfEmpty().HtmlEncode()))
}

<script type="text/javascript">
    $(document).ready(function () {
        var result = $('#ForumSearchResult'),
            loading = false;

        // Sorting changed.
        $('.fsearch-actions').on('change', '.artlist-action-select', function (e) {
            var select = $(this),
                qname = select.data('qname'),
                url = select.data('url'),
                val = select.val();

            url = window.modifyUrl(url, qname, val);
            window.setLocation(url);
        });

        // Auto load more search hits.
        $(document).scroll( function() {           
            var container = result.find('.load-more:not(.loading)');

            if (container.visible(true, false, 'vertical') && !loading) {
                var newPage = container.data('page'),
                    url = window.modifyUrl(window.location.href, 'i', newPage),
                    html, processImmediately = false;

                // IDs of already rendered topics, to avoid rendering them again when the list is extended.
                var renderedTopicIds = result.find('tr.topic').map(function() {
                    return $(this).data('id');
                }).get();

                //console.log(page + '. ' + url + '. ' + renderedTopicIds.toString());

                setTimeout(function () {
                    processImmediately = true;
                    processSearchResult(html, container, newPage);
                    html = null;
                }, 100);

                $.ajax({
                    cache: false,
                    type: 'POST',
                    async: true,
                    url: url,
                    data: { renderedTopicIds: renderedTopicIds },
                    beforeSend: function () {
                        loading = true;
                        container.addClass('loading').append(createCircularSpinner(20, true));
                    },
                    success: function (response) {
                        if (processImmediately) {
                            processSearchResult(response, container, newPage);
                        }
                        else {
                            html = response;
                        }
                    },
                    complete: function () {
                        loading = false;
                    },
                    error: function (objXml) {
                        result.find('.load-more:not(.loading)').removeClass('loading');

                        if (objXml && objXml.responseText.length > 0) {
                            displayNotification(objXml.responseText, 'error');
                        }
                    }
                });

            }
        });

        function processSearchResult(html, container, newPage) {
            if (html && html.length > 0) {
                // Replace empty tbody at table end by page representing tbody.
                container.replaceWith(html);

                // Update cumulative hit counter.
                $counter = $('#SearchHitsCount');
                $pageBody = result.find('tbody[data-page=' + newPage + ']');
                $counter.find('.cumulative-count').text($pageBody.data('cumulativehits'));
                if (!$pageBody.data('hasnextpage')) {
                    $counter.find('.more-hits-sign').hide();
                }
            }
        }

    });
</script>